<template>
  <div class="advice-container">
    <!-- 主按钮区域 -->
    <div class="action-section" :class="{ 'has-advice': adviceGiven }">
      <el-button
          v-if="!adviceGiven"
          type="primary"
          class="main-btn"
          icon="el-icon-magic-stick"
          :loading="loading"
          @click="submit1"
      >
        {{ loading ? '准备中...' : '获取我的专属心理建议' }}
      </el-button>

      <!-- 提问区域 -->
      <div v-if="adviceGiven" class="question-box">
        <el-input
            v-model="params.name"
            placeholder="请输入您的问题（例如：如何改善当前心理状态？）"
            class="question-input"
            clearable
            @keyup.enter.native="submit2"
        >
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
        </el-input>
        <el-button
            type="primary"
            class="ask-btn"
            :loading="isLoading"
            @click="submit2"
        >
          {{ isLoading ? '生成中...' : '立即提问' }}
        </el-button>
      </div>
    </div>

    <!-- 建议展示区域 -->
    <transition name="el-fade-in">
      <div v-if="adviceGiven" class="advice-card">
        <div class="card-header">
          <i class="el-icon-reading"></i>
          <h3>专属心理建议</h3>
        </div>
        <div class="advice-content" v-html="formattedAdvice"></div>
      </div>
    </transition>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      params: { name: '' },
      advice: '',
      adviceGiven: false,
      isLoading: false,
      loading:false
    }
  },
  computed: {
    formattedAdvice() {
      // 将换行符转换为HTML换行标签
      return this.advice.replace(/\n/g, '<br>');
    }
  },
  methods: {
    async submit1() {
      this.loading=true
      try {
        const user = JSON.parse(localStorage.getItem("user") || "{}");
        const res = await request.get("/grades/searchGrades", {
          params: { userId: user.id || '' }
        });

        if (res.code === '0') {
          if (res.data?.list?.length) {
            const scores = res.data.list[0];
            this.params.name = `心理学家您好，我的心理测评结果如下：
            - TAS评测成绩：${scores.gradesTAS}
            - ASLEC评测成绩：${scores.gradesASLEC}
            请根据以上结果，用正式但易懂的语气给出专业建议：
            1. 直接针对测评结果分析
            2. 分点说明改善建议
            3. 包含日常可操作的方法`;
            await this.submit2();
          } else {
            this.showMessage('未找到测评记录，请先完成心理测评', 'warning');
          }
        }
      } catch (error) {
        this.handleError(error);
      }
    },

    async submit2() {
      if (!this.params.name.trim()) {
        this.showMessage('请输入有效问题', 'warning');
        return;
      }

      this.isLoading = true;
      try {
        const res = await request.post("/ai", this.params, { timeout: 30000 });

        if (res.code === '0') {
          this.advice = res.data;
          this.adviceGiven = true;
          this.params.name = '';
          this.showMessage('建议生成成功', 'success');
        }
      } catch (error) {
        this.handleError(error);
      } finally {
        this.isLoading = false;
      }
    },

    showMessage(msg, type) {
      this.$message({
        message: msg,
        type: type,
        showClose: true,
        duration: 3000
      });
    },

    handleError(error) {
      console.error(error);
      this.showMessage(error.response?.data?.msg || '请求失败，请稍后重试', 'error');
    }
  }
}
</script>

<style scoped>
.advice-container {
  max-width: 800px;
  margin: 30px auto;
  padding: 20px;
}

.action-section {
  text-align: center;
  margin-bottom: 30px;
  transition: all 0.3s ease;

&.has-advice {
   margin-bottom: 20px;
 }
}

.main-btn {
  padding: 15px 30px;
  font-size: 16px;
  border-radius: 25px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: transform 0.2s;

&:hover {
   transform: translateY(-2px);
 }
}

.question-box {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.question-input {
  width: 70%;

::v-deep .el-input__inner {
  border-radius: 20px;
  padding-left: 40px;
  height: 45px;
}
}

.ask-btn {
  padding: 12px 30px;
  border-radius: 20px;
}

.advice-card {
  background: #ffffff;
  border-radius: 15px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  padding: 25px;
  margin-top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  color: #409EFF;

i {
  font-size: 24px;
  margin-right: 10px;
}

h3 {
  margin: 0;
  font-size: 20px;
}
}

.advice-content {
  line-height: 1.8;
  color: #606266;

::v-deep br {
  content: "";
  display: block;
  margin-bottom: 1em;
}
}

@media (max-width: 768px) {
  .question-box {
    flex-direction: column;
    align-items: center;
  }

  .question-input {
    width: 100%;
  }

  .ask-btn {
    width: 100%;
  }
}
</style>